package org.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.springboot.common.Result;
import org.example.springboot.entity.Dto.ConversationDTO;
import org.example.springboot.entity.Message;
import org.example.springboot.entity.Product;
import org.example.springboot.entity.User;
import org.example.springboot.mapper.MessageMapper;
import org.example.springboot.mapper.ProductMapper;
import org.example.springboot.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Service
public class MessageService {
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageService.class);

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ProductMapper productMapper;

    public Result<?> getMessagesByUserId(Long userId, Integer messageType, String userRole) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();

        // 根据用户角色构建不同的查询条件
        if ("ADMIN".equals(userRole)||"SUPER_ADMIN".equals(userRole)) {
            // 管理员可以查看所有消息
            // 不需要添加额外的条件
        } else {
            // 普通用户和商家只能查看自己发送或接收的消息
            queryWrapper.and(wrapper ->
                    wrapper.eq(Message::getSenderId, userId)
                            .or()
                            .eq(Message::getReceiverId, userId)
            );
        }

        if (messageType != null) {
            queryWrapper.eq(Message::getMessageType, messageType);
        }
        queryWrapper.orderByDesc(Message::getCreatedAt);

        return Result.success(messageMapper.selectList(queryWrapper));
    }

    public Result<?> markAsRead(Long id, Long currentUserId, String userRole) {
        try {
            Message message = messageMapper.selectById(id);
            if (message == null) {
                return Result.error("-1", "未找到消息");
            }

            // 权限检查：非管理员只能操作自己接收的消息
            if (!"ADMIN".equals(userRole) && !"SUPER_ADMIN".equals(userRole) && !message.getReceiverId().equals(currentUserId)) {
                return Result.error("-1", "无权操作此消息");
            }

            message.setStatus(1); // 已读
            message.setUpdatedAt(new Timestamp(System.currentTimeMillis()));

            int result = messageMapper.updateById(message);
            if (result > 0) {
                LOGGER.info("标记消息为已读成功，消息ID：{}", id);
                return Result.success();
            }
            return Result.error("-1", "标记消息为已读失败");
        } catch (Exception e) {
            LOGGER.error("标记消息为已读失败：{}", e.getMessage());
            return Result.error("-1", "标记消息为已读失败：" + e.getMessage());
        }
    }

    public Result<?> getUnreadCount(Long userId, String userRole) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();

        // 根据用户角色构建不同的查询条件
        if ("ADMIN".equals(userRole)||"SUPER_ADMIN".equals(userRole)) {
            // 管理员可以查看所有未读消息
            queryWrapper.eq(Message::getStatus, 0); // 未读
        } else {
            // 普通用户和商家只能查看自己接收的未读消息
            queryWrapper.eq(Message::getReceiverId, userId);
            queryWrapper.eq(Message::getStatus, 0); // 未读
        }

        return Result.success(messageMapper.selectCount(queryWrapper));
    }

    public Result<?> getMessagesByPage(Long userId, Integer messageType, Integer currentPage, Integer size, String userRole) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();

        // 根据用户角色构建不同的查询条件
        if ("ADMIN".equals(userRole)||"SUPER_ADMIN".equals(userRole)) {
            // 管理员可以查看所有消息
            // 不需要添加额外的条件
        } else {
            // 普通用户和商家只能查看自己发送或接收的消息
            queryWrapper.and(wrapper ->
                    wrapper.eq(Message::getSenderId, userId)
                            .or()
                            .eq(Message::getReceiverId, userId)
            );
        }

        if (messageType != null) {
            queryWrapper.eq(Message::getMessageType, messageType);
        }
        queryWrapper.orderByDesc(Message::getCreatedAt);

        Page<Message> page = new Page<>(currentPage, size);
        Page<Message> result = messageMapper.selectPage(page, queryWrapper);

        // 填充发送者信息
        result.getRecords().forEach(message -> {
            User sender = userMapper.selectById(message.getSenderId());
            message.setSender(sender);
        });

        return Result.success(result);
    }

    // 其他方法保持不变，但需要添加权限检查...

    // 获取对话详情（包括回复消息）
    public Result<?> getConversationDetail(Long conversationId, Long currentUserId, String userRole) {
        try {
            // 获取主对话消息
            Message mainMessage = messageMapper.selectById(conversationId);
            if (mainMessage == null) {
                return Result.error("-1", "对话不存在");
            }

            // 权限检查：非管理员只能查看自己参与的对话
            if (!"ADMIN".equals(userRole) && !"SUPER_ADMIN".equals(userRole) &&
                    !mainMessage.getSenderId().equals(currentUserId) &&
                    !mainMessage.getReceiverId().equals(currentUserId)) {
                return Result.error("-1", "无权查看此对话");
            }

            // 获取所有回复消息
            LambdaQueryWrapper<Message> replyWrapper = new LambdaQueryWrapper<>();
            replyWrapper.eq(Message::getConversationId, conversationId);
            replyWrapper.ne(Message::getId, conversationId); // 排除主消息
            replyWrapper.orderByAsc(Message::getCreatedAt);
            List<Message> replies = messageMapper.selectList(replyWrapper);

            // 填充发送者信息
            User mainSender = userMapper.selectById(mainMessage.getSenderId());
            mainMessage.setSender(mainSender);

            for (Message reply : replies) {
                User replySender = userMapper.selectById(reply.getSenderId());
                reply.setSender(replySender);
            }

            mainMessage.setReplies(replies);

            return Result.success(mainMessage);
        } catch (Exception e) {
            LOGGER.error("获取对话详情失败：{}", e.getMessage());
            return Result.error("-1", "获取对话详情失败：" + e.getMessage());
        }
    }

    // 获取用户的对话列表
    // 获取用户的消息列表（所有类型）
    public Result<?> getUserConversations(Long userId, String userRole) {
        try {
            LOGGER.info("获取用户消息列表，用户ID: {}, 用户角色: {}", userId, userRole);

            LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();

            // 使用统一的角色判断方法
            boolean isAdmin = "ADMIN".equalsIgnoreCase(userRole) || "SUPER_ADMIN".equalsIgnoreCase(userRole);

            if (isAdmin) {
                LOGGER.info("管理员查询所有消息");
                // 管理员可以查看所有消息
                // 不需要添加额外的条件
            } else {
                LOGGER.info("非管理员查询，用户ID: {}", userId);
                // 普通用户和商家只能查看自己参与的消息
                queryWrapper.and(wrapper ->
                        wrapper.eq(Message::getSenderId, userId)
                                .or()
                                .eq(Message::getReceiverId, userId)
                );
            }


            queryWrapper.isNull(Message::getParentId); // 只获取主消息（非回复）
            queryWrapper.orderByDesc(Message::getUpdatedAt);

            List<Message> messages = messageMapper.selectList(queryWrapper);
            LOGGER.info("查询到消息数量: {}", messages.size());

            // 如果没有消息，直接返回空列表
            if (messages.isEmpty()) {
                LOGGER.info("未找到符合条件的消息");
                return Result.success(new ArrayList<>());
            }

            // 创建 DTO 列表
            List<ConversationDTO> messageDTOs = new ArrayList<>();

            // 填充发送者和接收者信息
            for (Message message : messages) {
                User sender = userMapper.selectById(message.getSenderId());
                User receiver = userMapper.selectById(message.getReceiverId());

                message.setSender(sender);

                // 获取未读回复数量（仅对对话消息有意义）
                long unreadCount = 0;
                if (message.getMessageType() == 0) { // 对话消息
                    LambdaQueryWrapper<Message> unreadWrapper = new LambdaQueryWrapper<>();
                    unreadWrapper.eq(Message::getConversationId, message.getId());
                    unreadWrapper.eq(Message::getStatus, 0); // 未读

                    // 对于非管理员，只计算自己接收的未读消息
                    if (!isAdmin) {
                        unreadWrapper.eq(Message::getReceiverId, userId);
                    }

                    unreadCount = messageMapper.selectCount(unreadWrapper);
                } else {
                    // 对于非对话消息，直接使用消息本身的未读状态
                    if (!isAdmin && message.getReceiverId().equals(userId) && message.getStatus() == 0) {
                        unreadCount = 1;
                    }
                }

                // 创建 DTO 对象
                ConversationDTO dto = new ConversationDTO(
                        message,
                        unreadCount,
                        receiver != null ? receiver.getUsername() : "未知用户"
                );

                messageDTOs.add(dto);
            }

            LOGGER.info("成功构建 {} 个消息DTO", messageDTOs.size());
            return Result.success(messageDTOs);
        } catch (Exception e) {
            LOGGER.error("获取用户消息列表失败：{}", e.getMessage(), e);
            return Result.error("-1", "获取用户消息列表失败：" + e.getMessage());
        }
    }

    // 标记整个对话为已读
    @Transactional
    public Result<?> markConversationAsRead(Long conversationId, Long userId, String userRole) {
        try {
            // 首先检查对话是否存在且用户有权访问
            Message conversation = messageMapper.selectById(conversationId);
            if (conversation == null) {
                return Result.error("-1", "对话不存在");
            }

            // 权限检查：非管理员只能标记自己参与的对话
            if (!"ADMIN".equals(userRole) && !"SUPER_ADMIN".equals(userRole) &&
                    !conversation.getSenderId().equals(userId) &&
                    !conversation.getReceiverId().equals(userId)) {
                return Result.error("-1", "无权操作此对话");
            }

            LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Message::getConversationId, conversationId);
            queryWrapper.eq(Message::getStatus, 0); // 未读
            LOGGER.info("查询条件：对话ID={}, 未读状态=0", conversationId);

            // 对于非管理员，只标记自己接收的未读消息
            if (!"ADMIN".equals(userRole) && !"SUPER_ADMIN".equals(userRole)) {
                queryWrapper.eq(Message::getReceiverId, userId);
            }

            List<Message> unreadMessages = messageMapper.selectList(queryWrapper);
            LOGGER.info("找到 {} 条未读消息需要标记为已读", unreadMessages.size());

            int updateCount = 0;
            for (Message message : unreadMessages) {
                message.setStatus(1); // 已读
                message.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
                int result = messageMapper.updateById(message);
                
                if (result > 0) {
                    updateCount++;
                } else {
                    LOGGER.warn("消息ID {} 更新失败", message.getId());
                }
            }

            LOGGER.info("标记对话为已读完成，对话ID：{}，找到未读消息数：{}，成功更新数：{}", 
                       conversationId, unreadMessages.size(), updateCount);
            return Result.success();
        } catch (Exception e) {
            LOGGER.error("标记对话为已读失败：{}", e.getMessage(), e);
            return Result.error("-1", "标记对话为已读失败：" + e.getMessage());
        }
    }
    public Result<?> createMessage(Message message) {
        try {
            message.setCreatedAt(new Timestamp(System.currentTimeMillis()));
            message.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
            message.setSenderId(message.getSenderId());
            message.setReceiverId(message.getReceiverId());


            // 如果是对话消息且没有设置conversationId，则创建新的对话
            if (message.getMessageType() == 0 && message.getConversationId() == null) {
                message.setConversationId(System.currentTimeMillis()); // 使用时间戳作为临时对话ID
            }
            int result = messageMapper.insert(message);
            if (result > 0) {
                // 如果是新对话，更新conversationId为消息ID
                if (message.getConversationId() == null&&message.getParentId() == null) {
                    Message updateMsg = new Message();
                    updateMsg.setId(message.getId());
                    updateMsg.setConversationId(message.getId());
                    messageMapper.updateById(updateMsg);
                    message.setConversationId(message.getId());
                }
                LOGGER.info("创建消息成功，消息ID：{}", message.getId());
                return Result.success(message);
            }
            return Result.error("-1", "创建消息失败");
        } catch (Exception e) {
            LOGGER.error("创建消息失败：{}", e.getMessage());
            return Result.error("-1", "创建消息失败：" + e.getMessage());
        }
    }


    public Result<?> createMessageConversation(Long senderId, String content, Integer messageType, Long productId) {
        try {
            Message message = new Message();
            message.setSenderId(senderId);
            Product product = productMapper.selectById(productId);
            message.setReceiverId(product.getMerchantId());
            message.setContent(content);
            message.setMessageType(messageType);
            message.setProductId(productId);
            message.setStatus(0);
            message.setCreatedAt(new Timestamp(System.currentTimeMillis()));
            message.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
            message.setParentId(senderId);
            int result = messageMapper.insert(message);
            message.setConversationId(message.getId());
            messageMapper.updateById(message);
            System.out.println( message);
            if (result > 0) {
                LOGGER.info("创建消息成功，消息ID：{}", message.getId());
                return Result.success(message);
            }
            return Result.error("-1", "创建消息失败");
        } catch (Exception e) {
            LOGGER.error("创建消息失败：{}", e.getMessage());
            return Result.error("-1", "创建消息失败：" + e.getMessage());
        }
    }
}